package com.huanzhidadi.singleweb.delayqueue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DelayQueueManager implements CommandLineRunner {

    private DelayQueue<DelayedUser> delayQueue = new DelayQueue<>();
    private int messageCount = 5;
    private long delayTime = 5000;

    public void put() {
        log.info("加入延迟队列开始，当前队列：{}", delayQueue);
        DelayQueueProducer producer = new DelayQueueProducer(delayQueue, messageCount, delayTime, false);
        Thread producerThread = new Thread(producer);
        producerThread.start();
        while (!producer.isStopFlag()) {
            System.out.println(Thread.currentThread().getName() + "----睡眠一秒-----");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("加入延迟队列结束，当前队列长度：{}", delayQueue.size());
    }

    public void remove() {
        log.info("移出延迟队列开始，当前队列：{}", delayQueue);
        DelayQueueConsumer consumer = new DelayQueueConsumer(delayQueue, messageCount, false);
        Thread consumerThread = new Thread(consumer);
        consumerThread.start();
        while (!consumer.isStopFlag()) {
            System.out.println(Thread.currentThread().getName() + "----睡眠5秒-----");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 移出延迟队列开始时，加入延迟队列的操作还没有结束，会造成无法全部移出
            if (0 != delayQueue.size()) {
                log.info("再次检查延迟队列");
                this.remove();
            } else {
                log.info("移出延迟队列结束，当前队列长度：{}", delayQueue.size());
            }
        }

    }

    @Override
    public void run(String... args) throws Exception {
        remove();
    }
}
